import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/Login.vue'),
    meta: { guestOnly: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/login/Register.vue'),
    meta: { guestOnly: true }
  },
  {
    path: '/',
    component: () => import('@/components/Layout/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      { path: '', name: 'Dashboard', component: () => import('@/views/dashboard/Index.vue') },
      { path: 'customers', name: 'Customers', component: () => import('@/views/customer/ListView.vue') },
      { path: 'customers/add', name: 'CustomerAdd', component: () => import('@/views/customer/CreateView.vue') },
      { path: 'customers/edit/:id', name: 'CustomerEdit', component: () => import('@/views/customer/CreateView.vue') },
      { path: 'staff', name: 'Staff', component: () => import('@/views/staff/ListView.vue') },
      { path: 'staff/add', name: 'StaffAdd', component: () => import('@/views/staff/CreateView.vue') },
      { path: 'staff/edit/:id', name: 'StaffEdit', component: () => import('@/views/staff/CreateView.vue') },
      { path: 'business', name: 'Business', component: () => import('@/views/business/ListView.vue') },
      { path: 'business/add', name: 'BusinessAdd', component: () => import('@/views/business/CreateView.vue') },
      { path: 'business/edit/:id', name: 'BusinessEdit', component: () => import('@/views/business/CreateView.vue') },
      { path: 'workorders', name: 'WorkOrders', component: () => import('@/views/workorder/ListView.vue') },
      { path: 'workorders/add', name: 'WorkOrderAdd', component: () => import('@/views/workorder/CreateView.vue') },
      { path: 'workorders/edit/:id', name: 'WorkOrderEdit', component: () => import('@/views/workorder/CreateView.vue') }
    ]
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: { template: '<div style="padding:40px;text-align:center;font-size:24px;color:#c00;">403 无权限访问</div>' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login')
  } else if (to.meta.guestOnly && authStore.isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router